<template>
    <view class="payment-container">
        <!-- 支付金额头部 -->
        <view class="payment-header">
            <text class="payment-amount">¥{{ paymentAmount }}</text>
        </view>

        <!-- 支付方式列表 -->
        <view class="payment-methods">
            <!-- 余额支付 -->
            <view class="payment-method-item" :class="{ 'selected': selectedMethod === 'balance' }"
                @click="selectPaymentMethod('balance')">
                <view class="method-left">
                    <text class="method-name">余额支付</text>
                    <text class="balance-info">当前余额{{ userBalance }}元</text>
                </view>
                <view class="method-right">
                    <uv-icon :name="selectedMethod === 'balance' ? 'checkmark-circle' : 'checkmark'"
                        :color="selectedMethod === 'balance' ? '#07C160' : '#999'" size="24" />
                </view>
            </view>

            <!-- 微信支付 -->
            <view class="payment-method-item" :class="{ 'selected': selectedMethod === 'wechat' }"
                @click="selectPaymentMethod('wechat')">
                <view class="method-left">
                    <view class="method-icon wechat-icon">
                        <uv-icon name="chat" color="#07C160" size="20" />
                    </view>
                    <text class="method-name">微信支付</text>
                </view>
                <view class="method-right">
                    <uv-icon :name="selectedMethod === 'wechat' ? 'checkmark-circle' : 'checkmark'"
                        :color="selectedMethod === 'wechat' ? '#07C160' : '#999'" size="24" />
                </view>
            </view>

            <!-- 支付宝支付 -->
            <view class="payment-method-item" :class="{ 'selected': selectedMethod === 'alipay' }"
                @click="selectPaymentMethod('alipay')">
                <view class="method-left">
                    <view class="method-icon alipay-icon">
                        <uv-icon name="zhifubao-circle-fill" color="#1677FF" size="20" />
                    </view>
                    <text class="method-name">支付宝支付</text>
                </view>
                <view class="method-right">
                    <uv-icon :name="selectedMethod === 'alipay' ? 'checkmark-circle' : 'checkmark'"
                        :color="selectedMethod === 'alipay' ? '#07C160' : '#999'" size="24" />
                </view>
            </view>
        </view>

        <!-- 支付按钮 -->
        <view class="payment-button-container">
            <uv-button text="立即支付" size="large" :color="'#1677FF'"
                customStyle="width: 100%; height: 88rpx; border-radius: 44rpx;" @click="handlePayment" />
        </view>
    </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { UserInfoManager } from '@/utils/userInfo'
import { useRequest } from '@/api'

const { API_ORDER_PAY, API_JIDAN_DETAIL_GET ,API_MEMBER_INFO} = useRequest()

// 路由参数
const orderId = ref('')
const paymentAmount = ref('0.00')
const userBalance = ref('0.00')
const backType = ref('')

// 支付方式选择
const selectedMethod = ref('balance') // 默认选择余额支付

// 选择支付方式
const selectPaymentMethod = (method: string) => {
    selectedMethod.value = method
}

// 获取支付方式对应的mode值
const getPaymentMode = (method: string) => {
    const modeMap: { [key: string]: string } = {
        'balance': 'balance',
        'wechat': 'wxpay',
        'alipay': 'alipay'
    }
    return modeMap[method] || 'wxpay'
}

// 处理支付
const handlePayment = async () => {
    if (!orderId.value) {
        uni.showToast({
            title: '订单ID不能为空',
            icon: 'none'
        })
        return
    }

    // 检查余额是否足够（如果选择余额支付）
    if (selectedMethod.value === 'balance') {
        const balance = parseFloat(userBalance.value)
        const amount = parseFloat(paymentAmount.value)
        if (balance < amount) {
            uni.showToast({
                title: '余额不足，请选择其他支付方式',
                icon: 'none'
            })
            return
        }
    }
    uni.showLoading({
        title: '支付中...'
    })
    try {
        const params = {
            id: orderId.value,
            isdriver: UserInfoManager.lastrole(),
            mode: getPaymentMode(selectedMethod.value)
        }

        const res = await API_ORDER_PAY(params)
        
        if (res.code === 1) {
            uni.showToast({
                title: '支付成功',
                icon: 'success'
            })

            // 通知订单列表页面刷新
            uni.$emit('refOrderList')
            if (backType.value === '1') {
                uni.navigateBack({ delta: 2 })
            } else {
                uni.navigateBack()
            }
            
        } else {
            uni.showToast({
                title: res.msg || '支付失败',
                icon: 'none'
            })
        }
    } catch (error) {
        uni.showToast({
            title: '支付失败',
            icon: 'none'
        })
    } finally {
        uni.hideLoading()
    }
}


const real_usage = ref(0)
const voucher = ref('')
// 统一通过 onLoad 获取路由参数，兼容 APP/H5/小程序
onLoad((options: Record<string, any>) => {
    const id = options?.id
    if (id) {
        try { orderId.value = decodeURIComponent(String(id)) } catch { orderId.value = String(id) }
    }
    const t = options?.type
    if (t !== undefined) {
        backType.value = String(t)
    }
})
const getOederList = async () => {
    const params = {
        id: orderId.value,
        isdriver: UserInfoManager.lastrole()
    }
    const res = await API_JIDAN_DETAIL_GET(params)
    if (res.code === 1) {
        real_usage.value = res.data.real_usage || 0
        voucher.value = res.data.voucher || ''
        paymentAmount.value = res.data.order_price
    }
}
const initFormData = async () => {
  const params = {
    isdriver: UserInfoManager.lastrole()
  }
  const res = await API_MEMBER_INFO(params)
  if (res.code === 1) {
    userBalance.value = res.data.balance || '0.00'
  }
}
onMounted(() => {
    getOederList()
    initFormData()
})
</script>

<style lang="scss" scoped>
.payment-container {
    min-height: 100vh;
    background: #f6f7f9;
    padding: 20rpx;
    padding-bottom: 120rpx;
}

/* 支付金额头部 */
.payment-header {
    background: #fff;
    padding: 60rpx 40rpx;
    text-align: center;
    border-radius: 16rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);

    .payment-amount {
        font-size: 48rpx;
        font-weight: 600;
        color: #333;
    }
}

/* 支付方式列表 */
.payment-methods {
    background: #fff;
    border-radius: 16rpx;
    margin-bottom: 40rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
    overflow: hidden;

    .payment-method-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 32rpx 24rpx;
        border-bottom: 1rpx solid #f0f0f0;
        background: #fff;
        transition: all 0.3s ease;

        &:last-child {
            border-bottom: none;
        }

        &:active {
            background: #f8f9fa;
        }

        &.selected {
            background: #f0f8ff;
            border-left: 4rpx solid #1677FF;
        }

        .method-left {
            display: flex;
            align-items: center;
            flex: 1;

            .method-icon {
                width: 40rpx;
                height: 40rpx;
                border-radius: 8rpx;
                display: flex;
                align-items: center;
                justify-content: center;
                margin-right: 16rpx;

                &.wechat-icon {
                    background: rgba(7, 193, 96, 0.1);
                }

                &.alipay-icon {
                    background: rgba(22, 119, 255, 0.1);
                }
            }

            .method-name {
                font-size: 32rpx;
                color: #333;
                font-weight: 500;
            }

            .balance-info {
                font-size: 26rpx;
                color: #666;
                margin-left: 16rpx;
            }
        }

        .method-right {
            flex-shrink: 0;
        }
    }
}

/* 支付按钮容器 */
.payment-button-container {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: #fff;
    padding: 20rpx 40rpx;
    border-top: 1rpx solid #f0f0f0;
    z-index: 999;
}
</style>